import { PageContainer } from "@ant-design/pro-components";
import { Button, Input, Form, Space, Image } from "antd";
import { connect } from "umi";
import { namespace } from "./configFile";
import { DeleteOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import styles from "./styles.less";
import UploadPreview from "@/components/UploadPreview";
import { getItem } from "@/utils/localstorage";
import { TOKEN } from "@/constants";

const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [form] = Form.useForm();
  const [editor, setEditor] = useState(null);
  const [brandImg, setBrandImg] = useState("");
  // 编辑器内容
  const [html, setHtml] = useState("");
  type InsertFnType = (url: string, alt: string, href: string) => void;
  const editorConfig = {
    placeholder: "请输入内容", // JS 语法
    MENU_CONF: {
      uploadImage: {
        fieldName: "file",
        server: "/spark-frontend/system/user/uploadPic",
        allowedFileTypes: ["image/*"],
        headers: {
          clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
          Authorization: getItem(TOKEN),
        },

        customInsert(res: any, insertFn: InsertFnType) {
          if (res?.code == 200) {
            let { data } = res;
            insertFn(data, "", "");
          }
        },
      },
    },
  };
  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
      callback: (res) => {
        setHtml(res.brandIntroduce || "");
        setBrandImg(res.brandLogoUrl);
        form.setFieldsValue({
          ...res,
          brandLogoUrl: res.brandLogoUrl,
        });
      },
    });
  }, []);

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          brandLogoUrl: brandImg,
          brandIntroduce: html == "<p><br></p>" ? "" : html,
        },
        callback: () => {},
      });
    }
  };

  return (
    <PageContainer>
      <div className={styles.setting}>
        <Form form={form} className={styles.form}>
          <Form.Item
            label="品牌Id"
            name="tenantId"
            rules={[{ required: true }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="品牌名称"
            name="brandName"
            rules={[
              { required: true, message: "品牌名称不能为空,长度不超过20个字" },
            ]}
          >
            <Input maxLength={20} placeholder="请输入" showCount />
          </Form.Item>

          <Form.Item
            label="品牌LOGO"
            name="brandLogoUrl"
            rules={[{ required: true, message: "品牌LOGO不能为空" }]}
          >
            {brandImg ? (
              <div className={styles.avatar_box}>
                <Image width={100} height={100} src={brandImg} />
                <a
                  onClick={() => {
                    form.setFieldsValue({ brandLogoUrl: "" });
                    setBrandImg("");
                  }}
                >
                  <DeleteOutlined
                    style={{ fontSize: "15px", color: "#ffffff" }}
                  />
                </a>
              </div>
            ) : (
              <UploadPreview
                onSuccess={(e) => {
                  form.setFieldsValue({ brandLogoUrl: e });
                  setBrandImg(e);
                }}
              />
            )}
          </Form.Item>
          <Form.Item label="品牌介绍" name="请输入" style={{ width: "100%" }}>
            <div id="courseIntroduce">
              <Toolbar
                editor={editor}
                defaultConfig={{}}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => setHtml(editor.getHtml())}
                mode="default"
                style={{ height: "300px", overflowY: "hidden" }}
              />
            </div>
          </Form.Item>
          <div style={{ width: "100%", textAlign: "center" }}>
            <Button
              loading={submitLoading}
              size="large"
              type="primary"
              onClick={submitForm}
            >
              提交
            </Button>
          </div>
        </Form>
      </div>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
